<template>
  <el-card style="width: 80%; height: 95%; margin:20px auto 0px; padding: 5px 10px;position: relative">
    <div style="font-size: 20px;color: black; margin-bottom: 20px;">
      <button style="width: 7px; height: 20px; border-radius: 3px; background-color: rgb(41, 132, 248); border-width: 0; padding: 0"></button>
      <span style="margin-left: 10px;">待处理签约</span>
    </div>
    <el-form label-width="70px" label-position="right" :inline="true" style="position: relative">
      <el-form-item label="签约状态">
        <el-select placeholder="请选择" v-model="searchSigningForm.status" @change="loadSigning">
          <el-option label="请选择" value="0"></el-option>
          <el-option label="待审核" value="待审核"></el-option>
          <el-option label="待支付" value="待支付"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="签约机构">
        <el-select placeholder="请选择" v-model="searchSigningForm.institute" @change="loadSigning">
          <el-option label="请选择" value="0"></el-option>
          <el-option v-for="item in institutionArr" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生">
        <el-select placeholder="请选择" v-model="searchSigningForm.doctor" @change="loadSigning">
          <el-option label="请选择" value="0"></el-option>
          <el-option v-for="item in doctorArr" :label="item.doctorName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="position: absolute; right: 0;">
        <el-button plain @click="exportData">导出</el-button>
      </el-form-item>
      <br>
      <el-form-item label="服务项目">
        <el-select placeholder="请选择" v-model="searchSigningForm.item" @change="loadSigning">
          <el-option label="请选择" value="0"></el-option>
          <el-option v-for="item in serviceItemsArr" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="~"
            start-placeholder="请选择日期"
            end-placeholder="请选择日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            @change="loadSigning"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="请输入关键字" style="width:400px;" :suffix-icon="Search" v-model="content" @keydown.enter="loadSigning"></el-input>
      </el-form-item>
    </el-form>

    <el-table :data="SigningArr ? SigningArr.slice((currentPage - 1) * pageSize, currentPage * pageSize) : null" ref="tableRef" style="width: 100%;" height=655px
              :header-cell-style="{ textAlign: 'center', background: 'rgb(249,249,249)', height: '55px', color: 'rgb(51,51,51)', fontWeight: '200'}"
              :row-style="{ height:'60px' }"
              :cell-style="{ textAlign: 'center', padding:'0px' }"
              :row-class-name="setTableRow"
              :cell-class-name="cellStyle">
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="signedContractId" label="编号" :width="flexColumnWidth('signedContractId',SigningArr)"/>
      <el-table-column prop="name" label="签约人姓名" :width="flexColumnWidth('name',SigningArr)"  />
      <el-table-column prop="idcard" label="身份证号" :width="flexColumnWidth('idcard',SigningArr)"/>
      <el-table-column prop="phone" label="手机号码" :width="flexColumnWidth('phone',SigningArr)"/>
      <el-table-column prop="status" label="签约状态" :width="flexColumnWidth('status',SigningArr)"/>
      <el-table-column prop="doctorId" label="签约医生"  :formatter="doctorFormatter"/>
      <el-table-column prop="serviceItemsId" label="签约服务" :formatter="itemsFormatter"/>
      <el-table-column prop="updateTime" label="最后修改时间" :width="flexColumnWidth('updateTime',SigningArr)"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="toDetail(scope.$index)">查看详情</el-button>
          <el-button link type="primary" size="small" @click="toEdit(scope.$index)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="SigningArr.length"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :style="paginationStyle">>
    </el-pagination>
  </el-card>
</template>

<script setup>
import {onMounted, ref, nextTick, onUnmounted} from "vue";
  import axios from "axios";
  import qs from "qs";
  import {ElMessage} from "element-plus";
  import router from "@/router";
  import { Search } from '@element-plus/icons-vue'

  const institutionArr = ref([]);
  const doctorArr = ref([]);
  const serviceItemsArr = ref([]);
  onMounted(() => {
    loadData(institutionArr,'institution');
    loadData(doctorArr,'user');
    loadData(serviceItemsArr,'items');
  });

  const dateRange = ref([]);
  const searchSigningForm = ref({status:'', institute:'', doctor:'', item:''});
  const content = ref('');
  const allSigningArr = ref([]);
  const SigningArr = ref([]);

  onMounted(() => {
    loadSigning();
  });

  const loadSigning = ()=>{
    SigningArr.value = [];
    let data = qs.stringify(searchSigningForm.value);
    axios.get(BASE_URL+'/hhmc/sign/select?' + data).then((response)=>{
      if(response.data.code == 2000){
        allSigningArr.value = response.data.data;
        if (dateRange.value.length == 0) {
          SigningArr.value = allSigningArr.value;
        }
        else {
          const startTime = new Date(dateRange.value[0]);
          const endTime = new Date(dateRange.value[1]);
          for (let i = 0; i < allSigningArr.value.length; i++) {
            const oneSigning = allSigningArr.value[i];
            const updateTime = new Date(oneSigning.updateTime);
            if (updateTime >= startTime && updateTime <= endTime) {
              SigningArr.value.push(oneSigning);
            }
          }
        }
        for (let j = SigningArr.value.length - 1; j >= 0; j--) {
          if (SigningArr.value[j].status == '已完成' || SigningArr.value[j].status == '已驳回') {
            SigningArr.value.splice(j, 1);
          }
        }
        if (content.value != '') {
          for (let k = SigningArr.value.length - 1; k >= 0; k--) {
            const valuesArray = Object.values(SigningArr.value[k]).map(String);
            let isIncluded = valuesArray.some(value => value.includes(content.value));
            if (!isIncluded) {
              SigningArr.value.splice(k, 1);
            }
          }
        }
        SigningArr.value.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime));
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }

  const doctorFormatter = (row,column,cellValue,index)=>{
      if(!doctorArr.value){
      return cellValue;
    }
    for(let item of doctorArr.value) {
      if (item.id == cellValue) {
        cellValue = item.doctorName;
      }
    }
    return cellValue;
  }

  const itemsFormatter = (row,column,cellValue,index)=>{
    if(!serviceItemsArr.value){
      return cellValue;
    }
    for(let item of serviceItemsArr.value) {
      if (item.id == cellValue) {
        cellValue = item.name;
      }
    }
    return cellValue;
  }

  const toDetail = (id) => {
    router.push('/signingDetail?id=' + SigningArr.value[id].id)
  };

  const toEdit = (id) => {
    router.push('/editSigning?id=' + SigningArr.value[id].id)
  };

  const exportData = () => {
    ElMessage.success('导出成功!');
  };

  const tableRef = ref(null);
  const paginationStyle = ref({});
  const getOffsetTopRelativeToDocument = (element) => {
    const rect = element.getBoundingClientRect();
    return rect.top + window.pageYOffset;
  };

  const getTableBottomPosition = () => {
    const tableElement = tableRef.value.$el;
    const bottomPosition = getOffsetTopRelativeToDocument(tableElement) + tableElement.offsetHeight;
    console.log("Table bottom Position:", bottomPosition);

    if (bottomPosition < (window.innerHeight - 50)) {
      paginationStyle.value = { textAlign:'center', position:'absolute', bottom:'5px', right:'5px' };
    } else {
      paginationStyle.value = { textAlign:'center', marginTop:'20px', marginBottom:'5px', display:'flex',  justifyContent:'flex-end'};
    }
  };

  onMounted(() => {
    nextTick(() => {
      getTableBottomPosition();
    });
    // 监听窗口大小变化
    window.addEventListener('resize', getTableBottomPosition);
  });

  // 清除事件监听器
  onUnmounted(() => {
    window.removeEventListener('resize', getTableBottomPosition);
  });

  const currentPage = ref(1); //当前页 刷新后默认显示第一页
  const pageSize = ref(10); //每一页显示的数据量 此处每页显示10条数据

  const handleCurrentChange = (page) => {
    currentPage.value = page; //每次点击分页按钮，当前页发生变化
  }

  const setTableRow = (row) => {
    if (row.rowIndex % 2 == 0) {
      return 'j-row';
    } else {
      return 'o-row';
    }
    return '';
  }

  const cellStyle = (row, column, rowIndex, columnIndex) => {
        if (row.column.property == 'status') {
          if (row.row.status == '待审核') {
            return "cell_success";
          }
          else if (row.row.status == '待支付') {
            return "cell_process";
          }
          else if (row.row.status == '已驳回') {
            return "cell_fail";
          }
        }
      return "";
  }

</script>

<style scoped>
  :deep(.el-select) {
    width: 220px;
    .el-select__wrapper {
      height: 45px;
    }
  }

  :deep(.el-form-item__label) {
    height: 45px;
    line-height: 45px;
    color: #999999;
  }

  .el-form .el-button {
    width: 70px;
    height: 45px;
    font-size: 15px;
    border-color: #409EFF;
    background-color: white;
    color: #409EFF;
  }
  .el-form .el-button:hover {
    background-color: #409EFF !important;
    color: white !important;
  }

  :deep(.el-input__wrapper) {
    height: 45px;
  }

  :deep(.el-form .el-input) {
    width: 220px;
    .el-input__inner{
      border:0;
      height: 45px;
    }
    .el-input__icon{
      height: 45px;
      font-size: 18px;
    }
  }

  :deep(.el-pagination .el-input) {
    .el-input__wrapper{
      height: 35px;
      .el-input__inner{
        border:0;
        height: 35px;
      }
    }
  }

  :deep(.el-table) {
    background: white;
    .j-row {
      background: white;
    }
    .o-row {
      background: rgb(242,247,251);
    }
    .cell_success {
      color: rgb(117,281,187);
    }
    .cell_process {
      color: rgb(253,221,128);
    }
    .cell_fail {
      color: rgb(249,116,149);
    }
  }
</style>